<script lang="jsx" setup>
import { computed, nextTick, ref } from 'vue';
import { Button } from 'ant-design-vue';
import { DeleteOutlined, EditOutlined } from '@ant-design/icons-vue';
import Table from '@/components/common/table.vue';
import CommonSearch from '@/components/common/common-search.vue';
import Modal from '@/components/common/modal.vue';
import {
  addMold,
  addRecord,
  exportMold,
  recorddelete,
  scrapMold,
  updateMold
} from '@/service/api/modules/workwear/mold-management';
import Form from '@/components/common/form.vue';
import Add from './modules/add.vue';
import List from './modules/list.vue';
import Records from './modules/records.vue';

const commonSearchRef = ref(null);
const tableRef = ref(null);
const searchParams = ref({
  moldNo: null,
  moldState: null,
  time: null
});

const noticeStateList = ref([
  {
    value: 1,
    label: '生效'
  },
  {
    value: 2,
    label: '报废'
  },
  {
    value: 3,
    label: '暂停'
  },
  {
    value: 4,
    label: '调出'
  }
]);

const searchFormList = [
  {
    type: 'input',
    key: 'moldNo',
    label: '模具编号',
    placeholder: '请输入模具编号',
    span: 24,
    md: 12,
    lg: 8,
    xl: 8,
    xxl: 6
  },
  {
    type: 'select',
    key: 'moldState',
    label: '状态',
    placeholder: '请输入状态',
    span: 24,
    md: 12,
    lg: 8,
    xl: 8,
    xxl: 6,
    selectOptions: noticeStateList
  },
  {
    type: 'dateRangePicker',
    key: 'time',
    label: '日期',
    span: 24,
    md: 12,
    lg: 10,
    xl: 8,
    xxl: 6
  }
];

const column = [
  {
    key: 'dataIndex',
    dataIndex: 'dataIndex',
    title: '序号',
    width: 70,
    fixed: 'left',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'moldNo',
    dataIndex: 'moldNo',
    title: '模具型号',
    align: 'center',
    checked: true,
    ellipsis: true,
    fixed: 'left',
    width: 180,
    customRender: ({ record }) => {
      return (
        <Button type="link" onClick={() => handleListOpen(record)}>
          {record.moldNo}
        </Button>
      );
    }
  },
  {
    key: 'moldStateName',
    dataIndex: 'moldStateName',
    title: '状态',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 100
  },
  {
    key: 'moldTypeName',
    dataIndex: 'moldTypeName',
    title: '模具类型',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 120
  },
  {
    key: 'applyTypeName',
    dataIndex: 'applyTypeName',
    title: '申请类型',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 120
  },
  {
    key: 'boardMaterial',
    dataIndex: 'boardMaterial',
    title: '板材',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 100
  },
  {
    key: 'moldTypeNames',
    dataIndex: 'moldTypeNames',
    title: '使用寿命',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 160,
    customRender: ({ record }) => {
      if (record.moldTypeName === '软模') {
        return '20万次';
      }
      if (record.moldTypeName === '硬模') {
        return '12万次';
      }
      return '';
    }
  },
  {
    key: 'moldTypeName1',
    dataIndex: 'moldTypeName1',
    title: '管控研磨冲次',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 160,
    customRender: ({ record }) => {
      if (record.moldTypeName === '软模') {
        return '4万次';
      }
      if (record.moldTypeName === '硬模') {
        return '3万次';
      }
      return '';
    }
  },
  {
    key: 'boardThick',
    dataIndex: 'boardThick',
    title: '板厚(MM)',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 160
  },
  {
    key: 'punchTotal',
    dataIndex: 'punchTotal',
    title: '总使用次数',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 160
  },
  {
    key: 'grindPunchTotal',
    dataIndex: 'grindPunchTotal',
    title: '研磨后累计使用次数',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 190
  },
  {
    key: 'moldAddress',
    dataIndex: 'moldAddress',
    title: '存放位置',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 100
  },
  {
    key: 'applyBy',
    dataIndex: 'applyBy',
    title: '申请人',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 100
  },
  {
    key: 'applyDate',
    dataIndex: 'applyDate',
    title: '申请时间',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 180
  },
  {
    key: 'moldInDate',
    dataIndex: 'moldInDate',
    title: '入场日期',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 180
  },
  {
    key: 'supplier',
    dataIndex: 'supplier',
    title: '供应商',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 120
  },
  {
    key: 'repealBy',
    dataIndex: 'repealBy',
    title: '报废人',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 120
  },
  {
    key: 'repealDate',
    dataIndex: 'repealDate',
    title: '报废日期',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 180
  },
  {
    key: 'repealRemark',
    dataIndex: 'repealRemark',
    title: '报废原因',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 150
  },
  {
    key: 'remark',
    dataIndex: 'remark',
    title: '备注',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 180
  }
  // {
  //   key: 'table-cz',
  //   dataIndex: 'table-cz',
  //   title: '操作',
  //   align: 'center',
  //   checked: true,
  //   ellipsis: true,
  //   width: 180,
  //   fixed: 'right',
  //   customRender: ({ record }) => {
  //     return (
  //       <div>
  //         <Button
  //           type="link"
  //           danger
  //           class="pl-3px pr-3px"
  //           v-hasAuth={[['stamping-die-management:mold-management:del']]}
  //           onClick={() => {
  //             del(record);
  //           }}
  //         >
  //           删除
  //         </Button>
  //         <Button
  //           type="link"
  //           class="pl-3px pr-3px"
  //           v-hasAuth={[['stamping-die-management:mold-management:update']]}
  //           onClick={() => {
  //             handleOpen(record);
  //           }}
  //         >
  //           修改
  //         </Button>
  //         <Button
  //           type="link"
  //           class="pl-3px pr-3px"
  //           onClick={() => handleScrapOpen(record)}
  //           v-hasAuth={[['stamping-die-management:mold-management:scrap']]}
  //         >
  //           报废
  //         </Button>
  //       </div>
  //     );
  //   }
  // }
];

const searchData = computed(() => {
  const params = {
    ...searchParams.value
  };
  if (searchParams.value?.[0]) {
    params.startTime = dayjs(searchParams.value.time[0]).format('YYYY-MM-DD');
    params.endTime = dayjs(searchParams.value.time[1]).format('YYYY-MM-DD');
  }
  delete params.time;
  return params;
});

function search() {
  tableRef.value.getData(1);
}

function reset() {
  nextTick(() => {
    searchParams.value = {
      keywords: null,
      noticeState: null
    };
    search();
  });
}

const operateType = ref('add');
const modalVisible = ref(false);
const modleAddLoading = ref(false);
const currentRow = ref(null);
const addRef = ref(null);
function handleOpen(row) {
  currentRow.value = row;
  modalVisible.value = true;
  operateType.value = row ? 'edit' : 'add';
}

function handleClose() {
  modalVisible.value = false;
}
async function handleOk() {
  const addObj = {
    ...addRef.value
  };
  await addObj.validateForm();

  modleAddLoading.value = true;
  let pro;
  const params = {
    ...addObj.model
  };
  if (operateType.value === 'add') {
    pro = addMold(params);
  } else {
    pro = updateMold({
      ...params,
      moldUuid: currentRow.value.moldUuid
    });
  }
  pro
    .then(({ error }) => {
      if (!error) {
        window.$message.success(`${operateType.value === 'add' ? '新增' : '修改'}成功`);
        handleClose();
        reset();
      }
    })
    .finally(() => (modleAddLoading.value = false));

  console.log(params);
}

function hadnleDel(row) {
  console.log('row', row);

  window.$modal.confirm({
    title: `确定删除?`,
    onOk: () => {
      recorddelete(row.moldUuid).then(({ error }) => {
        if (!error) {
          window.$message.success('删除成功');
          search();
        }
      });
    },
    onCancel: () => {}
  });
}

function exportExcel() {
  exportMold({
    ...searchData.value
  });
}

const modalScrapVisible = ref(false);
const model = ref({
  repealRemark: null
});
const formList = [
  {
    type: 'textarea',
    key: 'repealRemark',
    label: '报废原因',
    rule: {
      required: true,
      message: '请输入报废原因',
      trigger: 'blur'
    },
    placeholder: '请输入报废原因',
    span: 24
  }
];
const modleScrapLoading = ref(false);
const formRef = ref(null);
const currentScrap = ref(null);
function handleScrapOpen(row) {
  modalScrapVisible.value = true;
  currentScrap.value = row;
}

function handleScrapClose() {
  modalScrapVisible.value = false;
  model.value.repealRemark = null;
}

async function handleScrapOk() {
  const params = {
    ...model.value,
    moldUuid: currentScrap.value.moldUuid
  };
  await formRef.value.validateForm();
  modleScrapLoading.value = true;
  scrapMold(params)
    .then(({ error }) => {
      if (!error) {
        window.$message.success('报废成功');
        handleScrapClose();
        reset();
      }
    })
    .finally(() => (modleScrapLoading.value = false));
}

function getBg(record) {
  if (Number(record.moldState) === 1) {
    if (record.moldTypeName === '硬模' && (record.punchTotal >= 100000 || record.grindPunchTotal >= 26000)) {
      return {
        backgroundColor: 'rgb(155, 240, 217)'
      };
    }
    if (record.moldTypeName === '软模' && (record.punchTotal >= 180000 || record.grindPunchTotal >= 36000)) {
      return {
        backgroundColor: 'rgb(239, 239, 136)'
      };
    }
  }
  if (Number(record.moldState) === 2) {
    return {
      backgroundColor: 'rgb(247, 109, 109)'
    };
  }
  return {};
}

const tableCustomRow = record => {
  return {
    style: getBg(record)
  };
};

const tabaleSelect = ref([]);
function tableSelectChange(val) {
  tabaleSelect.value = val;
}

const currentMoldId = ref(null);
const modalListVisible = ref(false);
const recordsRef = ref(null);
function handleListOpen(row) {
  currentMoldId.value = row.moldUuid;
  modalListVisible.value = true;
}

function handleListClose() {
  modalListVisible.value = false;
}

const recordsVisible = ref(false);
const recordsLoading = ref(false);

function handleRecordsOpen() {
  recordsVisible.value = true;
}

function handleRecordsClose() {
  recordsVisible.value = false;
}

async function handleRecordsOk() {
  const obj = { ...recordsRef.value };
  await obj.validateForm();
  const data = {
    ...obj.model
  };
  recordsLoading.value = true;
  addRecord(data)
    .then(({ error }) => {
      if (!error) {
        window.$message.success('保存成功');
        handleRecordsClose();
        reset();
      }
    })
    .finally(() => (recordsLoading.value = false));
}
</script>

<template>
  <div class="mold-management-page min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <CommonSearch
      ref="commonSearchRef"
      v-model:searchParams="searchParams"
      :form-list="searchFormList"
      :is-search="true"
      @search="search"
      @reset="reset"
    ></CommonSearch>

    <Table
      ref="tableRef"
      v-model:searchParams="searchData"
      :column="column"
      :show-row-selection="true"
      :auto-generate-uuid="true"
      class="h-full"
      :scroll="{ x: 3010, y: 'auto' }"
      is-init-get-data
      :table-custom-row="tableCustomRow"
      url="/qms/agv/frock/mold/record/list"
      @table-select-change="tableSelectChange"
    >
      <template #tableTitle>
        <AButton
          v-hasAuth="['stamping-die-management:mold-management:add']"
          type="primary"
          class="mini-btn mr-8px"
          size="small"
          ghost
          @click="handleOpen(null)"
        >
          <template #icon>
            <icon-ic-round-add class="align-sub text-icon" />
          </template>
          新增
        </AButton>
        <AButton
          v-hasAuth="['stamping-die-management:mold-management:update']"
          type="primary"
          class="mini-btn mr-8px"
          size="small"
          ghost
          :disabled="tabaleSelect.length != 1"
          @click="handleOpen(tabaleSelect[0])"
        >
          <template #icon>
            <EditOutlined class="align-sub" />
          </template>
          修改
        </AButton>

        <AButton
          v-hasAuth="['stamping-die-management:mold-management:del']"
          type="primary"
          danger
          class="mini-btn mr-8px"
          size="small"
          ghost
          :disabled="tabaleSelect.length != 1"
          @click="hadnleDel(tabaleSelect[0])"
        >
          <template #icon>
            <DeleteOutlined class="align-sub" />
          </template>
          删除
        </AButton>

        <AButton
          v-hasAuth="['stamping-die-management:mold-management:scrap']"
          type="primary"
          class="mini-btn mr-8px"
          size="small"
          ghost
          :disabled="tabaleSelect.length != 1"
          @click="handleScrapOpen(tabaleSelect[0])"
        >
          <template #icon>
            <em class="iconfont icon-baofei align-sub"></em>
          </template>
          报废
        </AButton>
        <AButton
          v-hasAuth="['stamping-die-management:mold-management:records']"
          type="primary"
          class="mini-btn mr-8px"
          size="small"
          ghost
          @click="handleRecordsOpen"
        >
          <template #icon>
            <span class="icon iconfont icon-jilubiao"></span>
          </template>
          记录
        </AButton>
        <AButton
          v-hasAuth="['stamping-die-management:mold-management:upload']"
          type="primary"
          size="small"
          ghost
          class="mini-btn mr-8px"
          @click="exportExcel"
        >
          <template #icon>
            <icon-ic-round-download class="align-sub text-icon" />
          </template>
          <span class="ml-3px">导出</span>
        </AButton>
      </template>
      <template #footer>
        <div class="flex gap-15px">
          <div style="display: flex; line-height: 14px; margin-top: 5px">
            <div style="width: 20px; height: 14px; background-color: rgb(155, 240, 217)"></div>
            <span>背景为硬模总冲次达到100000或者研磨后累计使用次数达到26000</span>
          </div>
          <div style="display: flex; line-height: 14px; margin-top: 5px">
            <div style="width: 20px; height: 14px; background-color: rgb(239, 239, 136)"></div>
            <span>背景为软模总冲次达到180000或者研磨后累计使用次数达到36000</span>
          </div>
          <div style="display: flex; line-height: 14px; margin-top: 5px">
            <div style="width: 20px; height: 14px; background-color: rgb(247, 109, 109)"></div>
            <span>背景为已报废模具</span>
          </div>
        </div>
      </template>
    </Table>

    <!-- 新增修改 -->
    <Modal
      v-model:visible="modalVisible"
      :title="`模具管理${operateType === 'add' ? '新增' : '修改'}`"
      width="800px"
      height="500px"
      :destroy-on-close="true"
      @close="handleClose"
    >
      <Add ref="addRef" :row-data="currentRow" :operate-type="operateType"></Add>
      <template #footer>
        <div class="modal-footer">
          <AButton :loading="modleAddLoading" type="primary" @click="handleOk">
            {{ operateType === 'add' ? '新增' : '修改' }}
          </AButton>
          <AButton @click="handleClose">关 闭</AButton>
        </div>
      </template>
    </Modal>

    <!-- 报废 -->

    <Modal
      v-model:visible="modalScrapVisible"
      title="报废"
      width="700px"
      height="232px"
      :destroy-on-close="true"
      @close="handleScrapClose"
    >
      <Form ref="formRef" v-model:model="model" :form-list="formList"></Form>
      <template #footer>
        <div class="modal-footer">
          <AButton :loading="modleScrapLoading" type="primary" @click="handleScrapOk">报废</AButton>
          <AButton @click="handleScrapClose">关 闭</AButton>
        </div>
      </template>
    </Modal>

    <Modal
      v-model:visible="modalListVisible"
      title="使用记录详情"
      width="80vw"
      height="70vh"
      :centered="true"
      :destroy-on-close="true"
      @close="handleListClose"
    >
      <List :mold-id="currentMoldId"></List>
      <template #footer>
        <div></div>
      </template>
    </Modal>

    <Modal
      v-model:visible="recordsVisible"
      title="使用记录填写"
      width="900px"
      height="488px"
      :centered="true"
      :destroy-on-close="true"
      @close="handleRecordsClose"
    >
      <Records ref="recordsRef"></Records>
      <template #footer>
        <div class="modal-footer">
          <AButton :loading="recordsLoading" type="primary" @click="handleRecordsOk">保存</AButton>
          <AButton @click="handleRecordsClose">关 闭</AButton>
        </div>
      </template>
    </Modal>
  </div>
</template>

<style lang="scss">
.mold-management-table {
  .ant-table-wrapper .ant-spin-nested-loading .ant-spin-container .ant-table {
    height: calc(100% - 90px);

    .bg-1 {
      td {
        background-color: rgb(155, 240, 217);
      }
    }

    .bg-2 {
      td {
        background-color: rgb(239, 239, 136);
      }
    }

    .bg-3 {
      td {
        background-color: rgb(247, 109, 109);
      }
    }
  }

  // .ant-table-wrapper .ant-table-pagination.ant-pagination {
  //   margin: 77px 0;
  // }
}
</style>
